package cmd

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"ckeadm/cmd/runner"
	"ckeadm/constants"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
)

// TODO: Not Watch create only

// deprecated, not use any longer, use <ckeadm status> replace
func WatchCommand() cli.Command {
	var watchFlags = []cli.Flag {
		runner.ConfigPathFlag,
		runner.PrivateKey,
		runner.LogLevelFlag,
	}

	return cli.Command {
		Name:   "watch",
		Usage:  "Bring the cluster install info",
		Action: runWatch,
		Flags:  watchFlags,
		Hidden: true,  // hidden this command because this ways is unwelcomed
	}
}


// runKubeletStart executes kubelet start logic.
func runWatch(ctx *cli.Context) error {
	var err error
	var privatekey string

	if privatekey, err = runner.GetPrivateKeyFile(ctx.String("private-key")); err != nil {
		return fmt.Errorf("error while get set connection private key, err: %s", err.Error())
	}
	if ctx.String("private-key") == constants.EmptyString {
		defer os.Remove(privatekey)
	}

	return runner.CkeadmLogsRunner(ctx, os.Stdout, constants.AnsibleUpDoneFile, GetInstallMsgsFromRemote(privatekey))
}

func GetInstallMsgsFromRemote(privatekey string) func(name, ip, clusterId, doneFile string) (logs []string) {
	return func(name, ip, clusterId, doneFile string) (logs []string) {
		logrus.Debugf("[I] send to %s, for get status ...\n", name)
		// #nosec
		out, _ := exec.Command("ssh", ip, "-o", "StrictHostKeyChecking=no", "-i", privatekey, "-T", fmt.Sprintf("cat %s/%s 2>/dev/null || echo", constants.AnsibleLogDir, doneFile)).CombinedOutput()

		logrus.Debugf("[I] get result from %s, %s\n", name, string(out))
		return runner.FilterSpace(strings.Split(strings.ReplaceAll(string(out), "\r", ""), "\n"))
	}
}